import React, { useState } from 'react'
import { Image, Text, View, navigateTo } from 'remax/one'
import RecycleView from 'remax-recycle-view/lib'
import { Button, Icon, Row, Space, Tag } from 'annar'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import useCloud from '@/hooks/use-cloud'
import Login from '@/components/login'
import styles from './index.css'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const OrderItem = ({ _id, promotion, casts, cost, createAt }: WBG.Order) => {
  return (
    <View className={styles.itemArea}>
      <View
        className={styles.itemBox}
        hoverClassName="hover"
        onTap={() => {
          navigateTo({ url: `/pages/cast/index?_id=${_id}` })
        }}
      >
        <Row className={styles.fullHeight} align="middle">
          <View className={styles.itemBoxLeft}>
            <Image
              className={styles.avatarImg}
              src={promotion.imgUrls[0]}
              mode="aspectFill"
            />
          </View>
          <Space className={styles.itemBoxRight} direction="vertical" size={6}>
            <View className="large-text ellipsis">{promotion.name}</View>
            <View className="small-text ellipsis">
              在 {casts.length} 个大屏上购买了{' '}
              {casts.reduce((pre, cur) => {
                return pre + cur.weeks.length
              }, 0)}{' '}
              个广告位
            </View>
            <Row justify="space-between" align="bottom">
              <Text className={styles.alarmText}>￥{cost}</Text>
              <Text className="small-text">{dayjs(createAt).fromNow()}</Text>
            </Row>
          </Space>
        </Row>
      </View>
    </View>
  )
}

export default () => {
  const { data, mutate } = useCloud('list-order')
  const [loading, setLoading] = useState(false)

  return (
    <Login>
      <View className={styles.addArea}>
        <Button
          className={styles.addButton}
          type="primary"
          onTap={() => {
            navigateTo({ url: `/pages/cast-add/index` })
          }}
        >
          <Icon type="add" color="#fff" />
        </Button>
      </View>
      {data &&
        (data.length ? (
          <RecycleView
            className={styles.mainArea}
            refresherEnabled
            refresherTriggered={loading}
            onRefresherRefresh={async () => {
              setLoading(true)
              await mutate()
              setLoading(false)
            }}
            data={data.map((v: WBG.Promotion) => ({ ...v, height: 220 }))}
            renderItem={(item, index) => {
              return <OrderItem {...((item as unknown) as WBG.Order)} />
            }}
          />
        ) : (
          <View className="empty-view small-text">您没有投放过广告</View>
        ))}
    </Login>
  )
}
